import moment from "moment";
import { ref, computed } from "vue";
import { getVppListAll } from "@/api/vppUser";
import {
  getMonthData,
  getPlan,
  getRegulatoryPerf,
  getExecuteInfo
} from "@/api/collaborativeInteractiveRresponse";
import { getVppTerminalList } from "@/api/vppTerminal";
export function useCalendarHook() {
  const loading = ref(false);
  // 获取 当前 年 月
  let nowYear = parseInt(moment().format("YYYY"));
  let nowMonth = parseInt(moment().format("MM"));
  let nowDay = moment().format("YYYY-MM-DD");
  let disabledYear = 2020;
  let disabledMonth = 12;
  const selYear = ref(nowYear);
  const selMonth = ref(nowMonth);
  const selValue = ref(nowDay);
  const calenderTitle = ref(`${nowYear} 年 ${nowMonth} 月`);

  const pervYearClick = computed(() => {
    // 上一年 是否可以点
    let time1 = moment(`${selYear.value - 1}-${selMonth.value}`);
    let time2 = moment(`${disabledYear}-${disabledMonth}`);
    if (time1.isAfter(time2)) {
      return true;
    } else {
      return false;
    }
  });
  const pervMonthClick = computed(() => {
    // 上一月 是否可以点
    let time1 = moment(`${selYear.value}-${selMonth.value}`).subtract(
      "1",
      "month"
    );
    let time2 = moment(`${disabledYear}-${disabledMonth}`);
    if (time1.isAfter(time2)) {
      return true;
    } else {
      return false;
    }
  });
  const nextYearClick = computed(() => {
    // 上一年 是否可以点
    // let time1 = moment(`${selYear.value + 1}-${selMonth.value}`);
    // let nowTime = moment();
    return true;
    // if (time1.isBefore(nowTime)) {
    //   return true;
    // } else {
    //   return false;
    // }
  });
  const nextMonthClick = computed(() => {
    // 上一年 是否可以点
    // let time1 = moment(`${selYear.value}-${selMonth.value}`).add("1", "month");
    // let nowTime = moment();
    return true;
    // if (time1.isBefore(nowTime)) {
    //   return true;
    // } else {
    //   return false;
    // }
  });

  const calendar = ref(null);
  const selectDate = async (val: string) => {
    let lYear = selYear.value;
    let lMonth = selMonth.value;
    if (val === "prev-year") {
      lYear = lYear - 1;
    }
    if (val === "prev-month") {
      if (lMonth === 1) {
        lMonth = 12;
        lYear = lYear - 1;
      } else {
        lMonth = lMonth - 1;
      }
    }
    if (val === "next-year") {
      lYear = lYear + 1;
    }
    if (val === "next-month") {
      if (lMonth === 12) {
        lMonth = 1;
        lYear = lYear + 1;
      } else {
        lMonth = lMonth + 1;
      }
    }
    if (lYear < disabledYear) {
      return;
    }
    if (lYear === disabledYear && lMonth < disabledMonth) {
      return;
    }
    // if (lYear > nowYear) {
    //   return;
    // }
    // if (lYear === nowYear && lMonth > nowMonth) {
    //   return;
    // }
    selYear.value = lYear;
    selMonth.value = lMonth;
    calenderTitle.value = `${selYear.value} 年 ${selMonth.value} 月`;
    await getMonthDataShowCalener();
    calendar.value.selectDate(val);
  };
  const dayIsHaveMonth = (day, month) => {
    let dateToCheck = day;
    let monthToCheck = month;
    let momentDate = moment(dateToCheck);
    let startOfMonth = moment(monthToCheck, "YYYY-MM").startOf("month");
    let endOfMonth = moment(monthToCheck, "YYYY-MM").endOf("month");
    let isInMonth =
      (momentDate.isAfter(startOfMonth) && momentDate.isBefore(endOfMonth)) ||
      momentDate.isSame(startOfMonth) ||
      momentDate.isSame(endOfMonth);
    return isInMonth;
  };
  const showBz = ref(false);
  const showTj = ref(false);
  const showYh = ref(false);
  const setActiveDay = async data => {
    loading.value = true;
    let isHave = dayIsHaveMonth(data.day, `${selYear.value}-${selMonth.value}`);
    if (isHave) {
      selValue.value = data.day;

      let item = calendarData.value.find(
        c => c.dataDate.split(" ")[0] === data.day
      );
      if (item) {
        if (item.dataType === 1) {
          showTj.value = true;
          showBz.value = true;
          showYh.value = true;
        } else {
          showTj.value = false;
          showBz.value = false;
          showYh.value = false;
        }
      } else {
        showBz.value = true;
        showTj.value = false;
        showYh.value = true;
      }
      if (
        selValue.value === nowDay ||
        moment(selValue.value).isBefore(moment(nowDay))
      ) {
        showBz.value = false;
        showYh.value = false;
        showTj.value = false;
      }
      // if (item) {
      //   if (item.dataType === 2 || item.dataType === 3) {
      //     showBz.value = false;
      //     showTj.value = false;
      //   } else {
      //     showBz.value = true;
      //     showTj.value = true;
      //   }
      // } else {
      //   showBz.value = true;
      //   showTj.value = false;
      // }
    }
    await getTopRightPlan();
    await getTopRightTwo();
    await getExecuteInfoData();
    loading.value = false;
  };

  const showDateItemCell = data => {
    let m = moment(data.day);
    return dayIsHaveMonth(data.day, `${selYear.value}-${selMonth.value}`)
      ? m.format("MM-DD")
      : "";
  };
  const vppList = ref([]);
  const calendarData = ref([]);
  const vppUserList = ref([]);
  const activeVppAndUser = ref([]);
  const terminalList = ref([]);
  const tSearch = ref("");
  const jterminalList = ref([]);
  const getMonthDataShowCalener = async () => {
    loading.value = true;
    let begin =
      moment(`${selYear.value}-${selMonth.value}`).format("YYYY-MM-") + "01";
    let days = moment(`${selYear.value}-${selMonth.value}`).daysInMonth();
    let end =
      moment(`${selYear.value}-${selMonth.value}`).format("YYYY-MM-") +
      "" +
      days;
    let data = await getMonthData({
      vppUserId: activeVppAndUser.value[1],
      begin: begin,
      end: end
    });
    calendarData.value = data || [];
    let item = calendarData.value.find(
      c => c.dataDate.split(" ")[0] === selValue.value
    );
    // if (item) {
    //   if (item.dataType === 2 || item.dataType === 3) {
    //     showBz.value = false;
    //     showTj.value = false;
    //   } else {
    //     showBz.value = true;
    //     showTj.value = true;
    //   }
    // } else {
    //   showBz.value = true;
    //   showTj.value = false;
    // }
    if (item) {
      if (item.dataType === 1) {
        showTj.value = true;
        showBz.value = true;
        showYh.value = true;
      } else {
        showTj.value = false;
        showBz.value = false;
        showYh.value = false;
      }
    } else {
      showBz.value = true;
      showTj.value = false;
      showYh.value = true;
    }
    if (
      selValue.value === nowDay ||
      moment(selValue.value).isBefore(moment(nowDay))
    ) {
      showBz.value = false;
      showYh.value = false;
      showTj.value = false;
    }
    loading.value = false;
  };
  const topRightData = ref({
    confirmMileage: 0,
    confirmUser: 0,
    planMileage: 0,
    planUser: 0
  });
  const topRightDataTwo = ref({
    adjustTheFrequency: "",
    adjustableMileage: "",
    adjustmentDuration: "",
    basedjustablePower: "",
    maxAdjustablePower: "",
    maxAdjustmentDuration: "",
    maxDownPegulationRate: "",
    maxUpPegulationRate: "",
    maxAdjustableStep: "",
    adjustThePeak: ""
  });
  const getTopRightPlan = async () => {
    let res = await getPlan({
      dataType: 2,
      date: selValue.value,
      vppId: activeVppAndUser.value[0],
      vppUserId: activeVppAndUser.value[1]
    });
    if (res) {
      topRightData.value = res;
    } else {
      topRightData.value = {
        confirmMileage: 0,
        confirmUser: 0,
        planMileage: 0,
        planUser: 0
      };
    }
  };
  const getTopRightTwo = async () => {
    let res = await getRegulatoryPerf({
      date: selValue.value,
      vppId: activeVppAndUser.value[0],
      vppUserId: activeVppAndUser.value[1]
    });
    if (res) {
      topRightDataTwo.value.maxAdjustableStep = res.maxAdjustableStep || "--";
      topRightDataTwo.value.adjustThePeak = res.adjustThePeak || "--";
      topRightDataTwo.value.adjustTheFrequency = res.adjustTheFrequency || "--";
      topRightDataTwo.value.adjustableMileage = res.adjustableMileage || "--";
      topRightDataTwo.value.adjustmentDuration = res.adjustmentDuration || "--";
      topRightDataTwo.value.basedjustablePower = res.basedjustablePower || "--";
      topRightDataTwo.value.maxAdjustablePower = res.maxAdjustablePower || "--";
      topRightDataTwo.value.maxAdjustmentDuration =
        res.maxAdjustmentDuration || "--";
      topRightDataTwo.value.maxDownPegulationRate =
        res.maxDownPegulationRate || "--";
      topRightDataTwo.value.maxUpPegulationRate =
        res.maxUpPegulationRate || "--";
    } else {
      topRightDataTwo.value = {
        adjustableMileage: "",
        maxAdjustableStep: "",
        adjustThePeak: "",
        adjustTheFrequency: "",
        adjustmentDuration: "",
        basedjustablePower: "",
        maxAdjustablePower: "",
        maxAdjustmentDuration: "",
        maxDownPegulationRate: "",
        maxUpPegulationRate: ""
      };
    }
  };

  const getTerminalList = async userId => {
    tSearch.value = "";
    let data = await getVppTerminalList({
      vppUserId: userId,
      current: 1,
      size: 10000000
    });
    terminalList.value = data.content || [];
    jterminalList.value = terminalList.value;
  };

  const search = () => {
    if (tSearch.value) {
      jterminalList.value = terminalList.value.filter(
        i => i.name.indexOf(tSearch.value) > -1
      );
    } else {
      jterminalList.value = terminalList.value;
    }
  };
  const centerData = ref([]);
  const errData = ref([]);
  const activeData = ref(null);
  const getExecuteInfoData = async () => {
    centerData.value = [];
    errData.value = [];
    activeData.value = null;
    let data = await getExecuteInfo({
      date: selValue.value,
      vppId: activeVppAndUser.value[0],
      vppUserId: activeVppAndUser.value[1]
    });
    centerData.value = data || [];
    centerData.value.forEach(item => {
      item.active = false;
    });
  };
  const setActiveCardLine = item => {
    // console.log(item, 'rrtwew')
    centerData.value.forEach(c => {
      if (c.id === item.id) {
        c.active = true;
      } else {
        c.active = false;
      }
    });
    // item.status = '3'
    // item.regulatoryAmount = '-100'
    activeData.value = item;
    errData.value = item.tExecuteDetails || [];
  };
  // const activeVppId = ref(null);
  getVppListAll().then(async res => {
    loading.value = true;
    vppList.value = res || [];
    if (vppList.value.length) {
      // activeVppId.value = vppList.value[0].id;
      vppUserList.value = vppList.value[0].vppUserResponse;
      if (vppList.value[0].vppUserResponse.length) {
        activeVppAndUser.value = [
          vppList.value[0].id,
          vppList.value[0].vppUserResponse[0].id
        ];
        await getTerminalList(activeVppAndUser.value[1]);
        await getTopRightPlan();
        await getTopRightTwo();
        await getMonthDataShowCalener();
        await getExecuteInfoData();
      } else {
        activeVppAndUser.value = [vppList.value[0].id];
      }
    }
    loading.value = false;
  });

  const showDateItemCellBottom = data => {
    let item = calendarData.value.find(
      c => c.dataDate.split(" ")[0] === data.day
    );
    if (item) {
      //
      if (item.dataType === 1) {
        return "编制中";
      }
      if (item.dataType === 2) {
        return "已确认";
      }
      if (item.dataType === 3) {
        return "已下发";
      }
    } else {
      return "";
    }
  };
  // const showDateItemCellBottom = computed(()=> {
  //   return (data)=> {
  //     let item = calendarData.value.find(c=> (c.dataDate).split(' ')[0] === data.day )
  //     console.log(item, 'gg')
  //     return dayIsHaveMonth(data.day, `${selYear.value}-${selMonth.value}`)
  //       ? "已确认"
  //       : "";
  //   }
  // })
  const handleChange = async () => {
    loading.value = true;
    await getTerminalList(activeVppAndUser.value[1]);
    await getTopRightPlan();
    await getTopRightTwo();
    await getMonthDataShowCalener();
    await getExecuteInfoData();
    loading.value = false;
  };
  // 指令类型 0:调节功率 1:调节水利阀门 2:调节机组 3:调节机组和阀门 4:调节机组和阀门和功率
  const formatType = type => {
    if (type === 0) {
      return "调节功率";
    }
    if (type === 1) {
      return "调节水利阀门";
    }
    if (type === 2) {
      return "调节机组";
    }
    if (type === 3) {
      return "调节机组和阀门";
    }
    if (type === 4) {
      return "调节机组和阀门和功率";
    }
  };
  // 调节延续 0:是(手动调节结束后将转为自动调节) 1否(手动调节结束后将不在下发指令直至下次调节)
  const formatType2 = type => {
    if (type === 0) {
      return "是(手动调节结束后将转为自动调节)";
    }
    if (type === 1) {
      return "否(手动调节结束后将不在下发指令直至下次调节)";
    }
  };
  const tjtimeFormat = value => {
    let h = 0;
    let min = 0;
    if (value === 0) {
      return "0h";
    } else {
      if (!value) {
        return "--";
      } else {
        if (value === "--") {
          return "--";
        } else {
          h = parseInt(value / 4);
          min = value % 4;
          if (min) {
            return `${h}h${min * 15}min`;
          } else {
            return `${h}h`;
          }
        }
      }
    }
  };
  return {
    nowYear,
    nowMonth,
    nowDay,
    disabledYear,
    disabledMonth,
    selYear,
    selMonth,
    selValue,
    calenderTitle,
    pervYearClick,
    pervMonthClick,
    nextYearClick,
    nextMonthClick,
    calendar,
    selectDate,
    dayIsHaveMonth,
    setActiveDay,
    showDateItemCell,
    showDateItemCellBottom,
    vppList,
    // activeVppId,
    vppUserList,
    activeVppAndUser,
    handleChange,
    topRightData,
    showBz,
    showTj,
    showYh,
    loading,
    getMonthDataShowCalener,
    topRightDataTwo,
    terminalList,
    tSearch,
    jterminalList,
    search,
    centerData,
    formatType,
    setActiveCardLine,
    errData,
    activeData,
    formatType2,
    tjtimeFormat
  };
}
